// index.js
import api from '../../utils/api'
const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'

Page({
  data: {
    userInfo: {
      avatarUrl: defaultAvatarUrl,
      nickName: '',
    },
    hasUserInfo: false,
    canIUseGetUserProfile: wx.canIUse('getUserProfile'),
    canIUseNicknameComp: wx.canIUse('input.type.nickname'),
  },
  
  onChooseAvatar: function (e) {
    const avatarUrl = e.detail.avatarUrl;
    const { nickName } = this.data.userInfo
    //wx.uploadFile post请求
      wx.uploadFile({
        url: api.BASE_URL+'uploadAvatar', // 后端上传头像接口地址
        filePath: avatarUrl,
        name: 'avatar',
        header: {
          'Authorization': wx.getStorageSync('Authorization'), // 从缓存中获取session_id
          // 其他头部信息...
        },
        success:(res)=> {
        // 服务器返回的响应数据，通常是JSON格式
        const data = JSON.parse(res.data);
        console.log(data);
        console.log(data.avatarUrl);
        // 根据服务器返回的头像URL更新数据
        if (data.success) {
          this.setData({
            "userInfo.avatarUrl": data.avatarUrl,
            hasUserInfo: nickName && data.avatarUrl && avatarUrl !== defaultAvatarUrl,
          });
        }
      },
      fail: function (error) {
        console.log('上传失败:', error);
      }
    });
  },
  onInputChange(e) {
    const nickName = e.detail.value
    console.log('nickName',nickName);
    const { avatarUrl } = this.data.userInfo
    this.setData({
      "userInfo.nickName": nickName,
      hasUserInfo: nickName && avatarUrl && avatarUrl !== defaultAvatarUrl,
    })
  },bindViewTap() {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
})
